package com.xhj.joffer.array;
import org.junit.Test;
/**
 * @author haijianxia pure_xhj@163.com
 * @Date 2021-09-16
 * @Time 16:40
 */
public class WhiteSpaceTo20 {
  public static void main(String[] args) {
	  String str="I love you and I can give you everything you what and can not achieve.";
    System.out.println("test01(str) = " + test01(str));
    System.out.println("str = " + str);

    System.out.println("test02(str) = " + test02(str));
  }
  /** 思路一: 转为char[] */
  @Test
  public static String test01(String str) {
  	System.out.println("\n=============test01==============");
  	System.out.println("思路一: 转为char[]");
  	long time01 = System.currentTimeMillis();

  	String result ="";
	  char[] chars = str.toCharArray();

	  int whiteSpaceCount=0;
    for (int i = 0; i < chars.length; i++) {
      if(chars[i]==' '){
        whiteSpaceCount++;
      }
    }

    char[] charsNew=new char[chars.length+whiteSpaceCount*2];
	  int charsNewIndex=0;
	  for (int i = 0; i < chars.length; i++) {
		  if(chars[i]==' '){
			  charsNew[charsNewIndex++]='%';
			  charsNew[charsNewIndex++]='2';
			  charsNew[charsNewIndex++]='0';
			  continue;
		  }
		  charsNew[charsNewIndex++]=chars[i];
	  }
    result=new String(charsNew);
	  str=result;

	  long time0101  = System.currentTimeMillis() - time01;
  	System.out.println("test01 耗时 =  " + time0101  + "ms");
  	System.out.println("=================================");

  	return result;
  }

  /** 思路二: String API */
  @Test
  public static String test02(String str) {
  	System.out.println("\n=============test02==============");
  	System.out.println("思路二: String API");
  	long time02 = System.currentTimeMillis();

	  str.replaceAll(" ","%20");

  	long time0202  = System.currentTimeMillis() - time02;
  	System.out.println("test02 耗时 =  " + time0202  + "ms");
  	System.out.println("=================================");

  	return str;
  }
}
